import React from 'react'


/* 
目的：数据展示列表+添加数据



*/



export default class Comment extends React.Component {
    state = {
        comments: [
            { id: 1, name: 'jack', content: '沙发！！！' },
            { id: 2, name: 'rose', content: '板凳~' },
            { id: 3, name: 'tom', content: '楼主好人' }
        ],

        txt: '',
        txtArea: ''
    }

    //  数据列表展示
    renderList = () => {
        const { comments } = this.state
        return comments.map(item => (<li key={item.id}>
            <h3>评论人：{item.name}</h3>
            <p>评论内容：{item.content}</p>
        </li>))
    }

    //  获取表单元素的值
    changHandle = (e) => {
        var { value, name } = e.target  //  获取表单值
        console.log(value, name);
        this.setState({
            [name]: value
        })
    }

    /* 添加评论 */
    addComment = () => {
        console.log(this.state, 777);
        //  准备一个对象  然后将这个对象 追加到数组中+表单值清空
        var obj = {
            id: this.state.comments.length + 1,
            name: this.state.txt,
            content: this.state.txtArea
        }
        this.setState({
            comments: [
                obj,
                ...this.state.comments
            ],
            txt: '',
            txtArea: ''
        })


    }


    render() {
        return (
            <div className="app">
                <div>
                    <input name='txt' className="user" value={this.state.txt} type="text" onChange={this.changHandle} placeholder="请输入评论人" />
                    <br />
                    <textarea
                        name='txtArea'
                        value={this.state.txtArea}
                        onChange={this.changHandle}
                        className="content"
                        cols="30"
                        rows="10"
                        placeholder="请输入评论内容"
                    />
                    <br />
                    <button onClick={this.addComment}>发表评论</button>
                </div>

                <div className="no-comment">暂无评论，快去评论吧~</div>
                <ul>
                    {/* <li>
                        <h3>评论人：jack</h3>
                        <p>评论内容：沙发！！！</p>
                    </li> */}
                    {/* comments.map(item => (<li key={item.id}>
                        <h3>评论人：{item.name}</h3>
                        <p>评论内容：{item.content}</p>
                    </li>)) */}

                    {this.renderList()}
                </ul>
            </div>
        )
    }
}

